package com.taobao.txc.resourcemanager.a;

import com.taobao.txc.common.LoggerInit;
import com.taobao.txc.common.LoggerWrap;
import com.taobao.txc.common.TxcContext;
import com.taobao.txc.common.c.B;
import com.taobao.txc.common.j;
import com.taobao.txc.parser.struct.TxcRuntimeContext;
import com.taobao.txc.parser.struct.TxcTable;
import com.taobao.txc.parser.struct.k;
import com.taobao.txc.parser.struct.m;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.commons.lang.StringUtils;
import org.springframework.jdbc.core.JdbcTemplate;

public class f
  implements com.taobao.txc.resourcemanager.a.a.d
{
  private static final LoggerWrap a = LoggerInit.logger;
  private static String b = "txc_undo_log";
  private static int c = 0;
  private static String d = a();
  
  private static String a()
  {
    String str = "";
    try
    {
      str = InetAddress.getLocalHost().toString();
    }
    catch (UnknownHostException localUnknownHostException) {}
    return str;
  }
  
  public static Set<String> a(JdbcTemplate paramJdbcTemplate)
  {
    int i = 1000;
    HashSet localHashSet = new HashSet();
    String str1 = com.taobao.txc.common.util.c.g.a(3);
    List localList = null;
    String str2 = "select id, server, status from " + b;
    StringBuilder[] arrayOfStringBuilder = new StringBuilder[2];
    arrayOfStringBuilder[0] = new StringBuilder(str2).append(" WHERE gmt_modified > '").append(str1).append("' limit ").append(i);
    arrayOfStringBuilder[1] = new StringBuilder(str2).append(" WHERE gmt_modified > to_date('").append(str1).append("','yyyy-mm-dd')");
    int j = 0;
    while (j < 2) {
      try
      {
        if (a.c()) {
          a.debug(arrayOfStringBuilder[j].toString());
        }
        localList = paramJdbcTemplate.queryForList(arrayOfStringBuilder[j].toString());
      }
      catch (Exception localException)
      {
        j++;
      }
    }
    if (localList == null) {
      return localHashSet;
    }
    Iterator localIterator = localList.iterator();
    while (localIterator.hasNext())
    {
      Object localObject = localIterator.next();
      String str3 = (String)((Map)localObject).get("server");
      if (str3 == null) {
        str3 = (String)((Map)localObject).get("SERVER");
      }
      localHashSet.add(str3);
    }
    if (localHashSet.size() > 0) {
      a.info(localHashSet.toString());
    }
    return localHashSet;
  }
  
  public static Set<String> b(JdbcTemplate paramJdbcTemplate)
  {
    int i = 1000;
    HashSet localHashSet = new HashSet();
    String str1 = com.taobao.txc.common.util.c.g.a(3);
    List localList = null;
    String str2 = "select id, server, status from " + b;
    StringBuilder[] arrayOfStringBuilder = new StringBuilder[2];
    arrayOfStringBuilder[0] = new StringBuilder(str2).append(" WHERE gmt_modified > '").append(str1).append("' limit ").append(i);
    arrayOfStringBuilder[1] = new StringBuilder(str2).append(" WHERE gmt_modified > to_date('").append(str1).append("','yyyy-mm-dd')");
    int j = 0;
    while (j < 2) {
      try
      {
        if (a.c()) {
          a.debug(arrayOfStringBuilder[j].toString());
        }
        localList = paramJdbcTemplate.queryForList(arrayOfStringBuilder[j].toString());
      }
      catch (Exception localException)
      {
        j++;
      }
    }
    if (localList == null) {
      return localHashSet;
    }
    Iterator localIterator = localList.iterator();
    while (localIterator.hasNext())
    {
      Object localObject = localIterator.next();
      Number localNumber = (Number)((Map)localObject).get("status");
      if (localNumber == null) {
        localNumber = (Number)((Map)localObject).get("STATUS");
      }
      String str3 = (String)((Map)localObject).get("server");
      if (str3 == null) {
        str3 = (String)((Map)localObject).get("SERVER");
      }
      if (localNumber.toString().equalsIgnoreCase(String.valueOf(m.d.a()))) {
        localHashSet.add(str3);
      }
    }
    if (localHashSet.size() > 0) {
      a.info(localHashSet.toString());
    }
    return localHashSet;
  }
  
  public static List<?> a(JdbcTemplate paramJdbcTemplate, String paramString, long paramLong)
  {
    String str = String.format("select server from %s where xid='%s' and branch_Id=%s", new Object[] { b, paramString, Long.valueOf(paramLong) });
    if (a.c()) {
      a.debug(str);
    }
    return paramJdbcTemplate.queryForList(str);
  }
  
  public static void a(com.taobao.txc.resourcemanager.b.a.a parama, TxcRuntimeContext paramTxcRuntimeContext)
  {
    String str = paramTxcRuntimeContext == null ? "null txc_undo_log" : paramTxcRuntimeContext.encode();
    a.info(String.format("[%d] %s [%s] [%s]", new Object[] { Long.valueOf(TxcContext.d()), str, b(parama), d }));
    if (a.b())
    {
      com.taobao.txc.common.a.a.a().c();
      Object localObject1 = null;
      try
      {
        parama.a(paramTxcRuntimeContext, b);
        return;
      }
      catch (SQLException localSQLException)
      {
        localObject1 = localSQLException;
        throw localSQLException;
      }
      finally
      {
        if (localObject1 == null) {
          a.a("tran.undolog", new Object[] { TxcContext.getCurrentXid(), "1", Long.valueOf(com.taobao.txc.common.a.a.a().c()), paramTxcRuntimeContext.j(), "", b(parama), str });
        } else {
          a.a("tran.undolog", new Object[] { TxcContext.getCurrentXid(), "0", Long.valueOf(com.taobao.txc.common.a.a.a().c()), paramTxcRuntimeContext.j(), localObject1.getMessage(), b(parama), str });
        }
      }
    }
    parama.a(paramTxcRuntimeContext, b);
  }
  
  public void a(com.taobao.txc.common.b paramb)
  {
    a(Arrays.asList(new com.taobao.txc.common.b[] { paramb }));
  }
  
  public List<List> a(List paramList, int paramInt)
  {
    ArrayList localArrayList1 = new ArrayList();
    int i = paramList.size() % paramInt == 0 ? paramList.size() / paramInt : paramList.size() / paramInt + 1;
    for (int j = 0; j < i; j++)
    {
      ArrayList localArrayList2 = new ArrayList();
      for (int k = j * paramInt; k <= paramInt * (j + 1) - 1; k++) {
        if (k <= paramList.size() - 1) {
          localArrayList2.add(paramList.get(k));
        }
      }
      localArrayList1.add(localArrayList2);
    }
    return localArrayList1;
  }
  
  public void a(List<com.taobao.txc.common.b> paramList)
  {
    if ((paramList == null) || (paramList.size() <= 0)) {
      return;
    }
    StringBuilder localStringBuilder = new StringBuilder();
    localStringBuilder.append("total:").append(paramList.size());
    HashMap localHashMap = new HashMap();
    Object localObject2;
    Object localObject3;
    synchronized (paramList)
    {
      localObject1 = paramList.iterator();
      while (((Iterator)localObject1).hasNext())
      {
        localObject2 = (com.taobao.txc.common.b)((Iterator)localObject1).next();
        if (((com.taobao.txc.common.b)localObject2).c().a() == com.taobao.txc.common.a.c.a())
        {
          com.taobao.txc.resourcemanager.a.c.a.a(((com.taobao.txc.common.b)localObject2).a(), ((com.taobao.txc.common.b)localObject2).b(), ((com.taobao.txc.common.b)localObject2).e(), ((com.taobao.txc.common.b)localObject2).d());
        }
        else
        {
          localObject3 = (List)localHashMap.get(((com.taobao.txc.common.b)localObject2).e());
          if (localObject3 == null)
          {
            localObject3 = new ArrayList();
            localHashMap.put(((com.taobao.txc.common.b)localObject2).e(), localObject3);
          }
          ((List)localObject3).add(localObject2);
        }
      }
    }
    ??? = localHashMap.keySet().iterator();
    while (((Iterator)???).hasNext())
    {
      localObject1 = (String)((Iterator)???).next();
      localStringBuilder.append(", ").append((String)localObject1).append(":").append(localHashMap.get(localObject1) == null ? 0 : ((List)localHashMap.get(localObject1)).size());
    }
    a.info(localStringBuilder.toString());
    ??? = null;
    Object localObject1 = localHashMap.keySet().iterator();
    while (((Iterator)localObject1).hasNext())
    {
      localObject2 = (String)((Iterator)localObject1).next();
      localObject3 = (List)localHashMap.get(localObject2);
      if ((localObject3 != null) && (((List)localObject3).size() > 0))
      {
        List localList1 = a((List)localObject3, 100);
        Iterator localIterator = localList1.iterator();
        while (localIterator.hasNext())
        {
          List localList2 = (List)localIterator.next();
          if (a.c())
          {
            localObject5 = localList2.iterator();
            while (((Iterator)localObject5).hasNext())
            {
              com.taobao.txc.common.b localb = (com.taobao.txc.common.b)((Iterator)localObject5).next();
              a.debug(String.format("%s:%d branchCommit %s", new Object[] { localb.a(), Long.valueOf(localb.b()), localObject2 }));
            }
          }
          Object localObject5 = null;
          if (localList2.size() > 0) {
            try
            {
              localObject5 = (com.taobao.txc.resourcemanager.b.a.a)com.taobao.txc.resourcemanager.b.b.a((String)localObject2).getConnection();
              a(localList2, (com.taobao.txc.resourcemanager.b.a.a)localObject5);
              if (a.c())
              {
                c += localList2.size();
                a.debug("total committed branches:" + c);
              }
              paramList.removeAll(localList2);
              localList2.clear();
            }
            catch (Exception localException)
            {
              if (localException.getMessage() != null)
              {
                if (((localException instanceof com.taobao.txc.common.b.c)) && (localException.getMessage().indexOf("not find datasource") != -1))
                {
                  a.info(String.format("branchCommit error code:%s message:%s", new Object[] { ((com.taobao.txc.common.b.c)localException).b().bd, localException.getMessage() }));
                  paramList.removeAll(localList2);
                  localList2.clear();
                  if (localObject5 == null) {
                    continue;
                  }
                  ((com.taobao.txc.resourcemanager.b.a.a)localObject5).close();
                  continue;
                }
                if (((localException instanceof SQLException)) && ((localException.getMessage().indexOf("read-only") != -1) || (localException.getMessage().indexOf("command denied") != -1) || (localException.getMessage().indexOf("not allowed") != -1)))
                {
                  a.info(String.format("branchCommit error code:%d state:%s message:%s", new Object[] { Integer.valueOf(((SQLException)localException).getErrorCode()), ((SQLException)localException).getSQLState(), localException.getMessage() }));
                  paramList.removeAll(localList2);
                  localList2.clear();
                  if (localObject5 == null) {
                    continue;
                  }
                  ((com.taobao.txc.resourcemanager.b.a.a)localObject5).close();
                  continue;
                }
              }
              if (??? == null) {
                ??? = localException.getMessage();
              }
            }
            finally
            {
              if (localObject5 != null) {
                ((com.taobao.txc.resourcemanager.b.a.a)localObject5).close();
              }
            }
          }
        }
      }
    }
    if (??? != null) {
      throw new com.taobao.txc.common.b.c((String)???);
    }
  }
  
  public void b(com.taobao.txc.common.b paramb)
  {
    com.taobao.txc.resourcemanager.b.a.b localb = com.taobao.txc.resourcemanager.b.b.a(paramb.e());
    a.info(String.format("[%d:%d] start branchRollback [%s]", new Object[] { Long.valueOf(j.a(paramb.a())), Long.valueOf(paramb.b()), localb.b() }));
    try
    {
      a(paramb, localb);
    }
    catch (Exception localException)
    {
      if ((localException instanceof com.taobao.txc.common.b.c)) {
        throw ((com.taobao.txc.common.b.c)localException);
      }
      if ((localException instanceof SQLException))
      {
        a.info(String.format("branchRollback error code:%d state:%s message:%s", new Object[] { Integer.valueOf(((SQLException)localException).getErrorCode()), ((SQLException)localException).getSQLState(), localException.getMessage() }));
        if ((localException.getMessage() != null) && ((localException.getMessage().indexOf("read-only") != -1) || (localException.getMessage().indexOf("command denied") != -1) || (localException.getMessage().indexOf("not allowed") != -1)))
        {
          a.info(String.format("Start failOver rollback branchId:[%d] [%s]", new Object[] { Long.valueOf(paramb.b()), localb.b() }));
          Iterator localIterator = com.taobao.txc.resourcemanager.b.b.b(localb);
          if (a(paramb, localIterator)) {
            return;
          }
        }
        throw ((SQLException)localException);
      }
      throw new SQLException(localException);
    }
  }
  
  public void a(com.taobao.txc.common.b paramb, com.taobao.txc.resourcemanager.b.a.a parama)
  {
    a(Arrays.asList(new com.taobao.txc.common.b[] { paramb }), parama);
  }
  
  public void a(Integer paramInteger)
  {
    int i = 100;
    int j = 7;
    if (paramInteger != null)
    {
      if (paramInteger.intValue() <= 0) {
        return;
      }
      j = paramInteger.intValue();
    }
    Iterator localIterator = com.taobao.txc.resourcemanager.b.b.a().keySet().iterator();
    while (localIterator.hasNext())
    {
      String str = (String)localIterator.next();
      com.taobao.txc.resourcemanager.b.a.b localb = (com.taobao.txc.resourcemanager.b.a.b)com.taobao.txc.resourcemanager.b.b.a().get(str);
      long l1 = System.currentTimeMillis();
      g localg = new g(this);
      try
      {
        a(localb, paramInteger.intValue(), i, localg);
      }
      catch (Exception localException)
      {
        long l2;
        a.info(String.format("clean old undo log ignore failed on dbKey:%s %s", new Object[] { str, localException.getMessage() }));
      }
      finally
      {
        long l3;
        long l4 = System.currentTimeMillis();
        a.info(String.format("clean old undo log dbKey:%s appName:%s dbName:%s total:%d with days:%d cost:%d ms", new Object[] { str, localb.c(), localb.b(), Long.valueOf(localg.a), Integer.valueOf(j), Long.valueOf(l4 - l1) }));
      }
    }
  }
  
  public void a(List<com.taobao.txc.common.b> paramList, com.taobao.txc.resourcemanager.b.a.a parama)
  {
    if (paramList.isEmpty()) {
      return;
    }
    StringBuilder localStringBuilder1 = new StringBuilder();
    StringBuilder localStringBuilder2 = new StringBuilder("delete from ");
    localStringBuilder2.append(b);
    localStringBuilder2.append(" where id in (");
    int i = 0;
    Object localObject1 = paramList.iterator();
    while (((Iterator)localObject1).hasNext())
    {
      com.taobao.txc.common.b localb = (com.taobao.txc.common.b)((Iterator)localObject1).next();
      if (i == 1) {
        localStringBuilder1.append(",");
      } else {
        i = 1;
      }
      localStringBuilder1.append(localb.b());
    }
    localObject1 = localStringBuilder1.toString();
    localStringBuilder2.append((String)localObject1).append(")");
    long l1 = System.currentTimeMillis();
    PreparedStatement localPreparedStatement = null;
    try
    {
      localPreparedStatement = parama.b().prepareStatement(localStringBuilder2.toString());
      localPreparedStatement.executeUpdate();
    }
    catch (Throwable localThrowable)
    {
      long l2;
      a.a(com.taobao.txc.common.b.b.I, localThrowable);
      if ((localThrowable instanceof SQLException)) {
        throw ((SQLException)localThrowable);
      }
      throw new SQLException(localThrowable);
    }
    finally
    {
      if (localPreparedStatement != null) {
        localPreparedStatement.close();
      }
      long l3 = System.currentTimeMillis();
      a.info(String.format("delete [%s] cost %d ms.", new Object[] { localObject1, Long.valueOf(l3 - l1) }));
    }
  }
  
  private TxcRuntimeContext a(String paramString, long paramLong, com.taobao.txc.resourcemanager.b.a.a parama)
  {
    String str1 = String.format("select * from %s where status = 0 and id = %d order by id desc for update", new Object[] { b, Long.valueOf(paramLong) });
    a.info(String.format("[%d:%d] [%s]", new Object[] { Long.valueOf(j.a(paramString)), Long.valueOf(paramLong), str1 }));
    ArrayList localArrayList = new ArrayList();
    long l1 = 0L;
    if (a.c()) {
      l1 = System.currentTimeMillis();
    }
    try
    {
      String str2 = parama.a(parama, str1);
      if (StringUtils.isNotEmpty(str2))
      {
        localTxcRuntimeContext = TxcRuntimeContext.decode(str2);
        localArrayList.add(localTxcRuntimeContext);
      }
    }
    finally
    {
      long l2;
      if (a.c())
      {
        long l3 = System.currentTimeMillis();
        a.debug(String.format("selectUndoLog:[%s] cost %d ms.", new Object[] { str1, Long.valueOf(l3 - l1) }));
      }
    }
    if ((localArrayList == null) || (localArrayList.size() == 0))
    {
      a.info(String.format("[%s:%d] no txc_undo_log", new Object[] { paramString, Long.valueOf(paramLong) }));
      return null;
    }
    if (localArrayList.size() > 1)
    {
      String str3 = String.format("[%s:%d] check txc_undo_log, trx info duplicate", new Object[] { paramString, Long.valueOf(paramLong) });
      a.info(str3);
      throw new com.taobao.txc.common.b.c(str3);
    }
    int i = 0;
    TxcRuntimeContext localTxcRuntimeContext = (TxcRuntimeContext)localArrayList.get(0);
    Iterator localIterator = localTxcRuntimeContext.c().iterator();
    while (localIterator.hasNext())
    {
      com.taobao.txc.parser.struct.c localc = (com.taobao.txc.parser.struct.c)localIterator.next();
      a.info(String.format("[%d:%d] [%d/%d] [%s]", new Object[] { Long.valueOf(j.a(paramString)), Long.valueOf(paramLong), Integer.valueOf(++i), Integer.valueOf(localTxcRuntimeContext.c().size()), localc.i() }));
    }
    return localTxcRuntimeContext;
  }
  
  protected void a(com.taobao.txc.resourcemanager.b.a.a parama, com.taobao.txc.parser.struct.c paramc)
  {
    TxcTable localTxcTable1 = paramc.c();
    TxcTable localTxcTable2 = paramc.e();
    String str = localTxcTable1.h() == null ? localTxcTable2.h() : localTxcTable1.h();
    k localk = com.taobao.txc.parser.b.b.a.a(parama, str);
    localTxcTable1.a(localk);
    localTxcTable2.a(localk);
  }
  
  protected void b(com.taobao.txc.resourcemanager.b.a.a parama, com.taobao.txc.parser.struct.c paramc)
  {
    String str1 = String.format("%s %s FOR UPDATE", new Object[] { paramc.f(), paramc.g() });
    String str2 = "";
    String str3 = "";
    StringBuilder localStringBuilder = new StringBuilder();
    long l = System.currentTimeMillis();
    try
    {
      TxcTable localTxcTable1 = paramc.e();
      str2 = localTxcTable1.toString();
      localStringBuilder.append("--Log:[");
      localStringBuilder.append(str2);
      localStringBuilder.append("]");
      TxcTable localTxcTable2 = new TxcTable();
      localTxcTable2.a(localTxcTable1.e());
      localTxcTable2.a(parama, str1);
      str3 = localTxcTable2.toString();
      localStringBuilder.append("--Db[");
      localStringBuilder.append(str3);
      localStringBuilder.append("]");
    }
    catch (SQLException localSQLException)
    {
      throw new com.taobao.txc.common.b.c(localSQLException, paramc.j() + ":" + paramc.k() + "checkDirtyRead error:" + localStringBuilder.toString());
    }
    finally
    {
      a.info("[" + j.a(paramc.j()) + ":" + paramc.k() + "]  [" + str1 + "]  [ cost " + (System.currentTimeMillis() - l) + " ms]");
    }
    if ((!str2.equals(str3)) && ((paramc.e != com.taobao.txc.parser.struct.d.b) || (!StringUtils.isEmpty(str3)))) {
      throw new com.taobao.txc.common.b.c(B.c.a(), "dirty read:" + localStringBuilder.toString());
    }
  }
  
  public static String a(com.taobao.txc.resourcemanager.b.a.a parama)
  {
    String str = null;
    try
    {
      Connection localConnection = parama.b();
      str = String.format("conn:%d:%B", new Object[] { Integer.valueOf(localConnection.hashCode()), Boolean.valueOf(localConnection.getAutoCommit()) });
    }
    catch (Throwable localThrowable) {}
    return str;
  }
  
  public static String b(com.taobao.txc.resourcemanager.b.a.a parama)
  {
    String str = null;
    try
    {
      str = parama.a().b();
    }
    catch (Throwable localThrowable) {}
    return str;
  }
  
  private void a(com.taobao.txc.common.b paramb, com.taobao.txc.resourcemanager.b.a.b paramb1)
  {
    com.taobao.txc.resourcemanager.b.a.a locala = null;
    try
    {
      locala = (com.taobao.txc.resourcemanager.b.a.a)paramb1.getConnection();
      locala.b().setAutoCommit(false);
      TxcRuntimeContext localTxcRuntimeContext = a(paramb.a(), paramb.b(), locala);
      if (localTxcRuntimeContext == null) {
        return;
      }
      for (int i = localTxcRuntimeContext.c().size(); i > 0; i--)
      {
        com.taobao.txc.parser.struct.c localc = (com.taobao.txc.parser.struct.c)localTxcRuntimeContext.c().get(i - 1);
        localc.e(paramb.a());
        localc.a(paramb.b());
        a.info(String.format("[%d:%d] [%s]", new Object[] { Long.valueOf(j.a(paramb.a())), Long.valueOf(paramb.b()), localc.i() }));
        a(locala, localc);
        if ((localc.d() == null) || (localc.d().isEmpty())) {
          b(locala, localc);
        }
        com.taobao.txc.resourcemanager.e.a.a(localc).a(locala);
      }
      a(paramb, locala);
      locala.b().commit();
    }
    catch (Exception localException)
    {
      if (locala != null) {
        locala.b().rollback();
      }
      throw localException;
    }
    finally
    {
      if (locala != null)
      {
        locala.b().setAutoCommit(true);
        locala.close();
      }
    }
  }
  
  private boolean a(com.taobao.txc.common.b paramb, Iterator<com.taobao.txc.resourcemanager.b.a.b> paramIterator)
  {
    while (paramIterator.hasNext())
    {
      com.taobao.txc.resourcemanager.b.a.b localb = (com.taobao.txc.resourcemanager.b.a.b)paramIterator.next();
      try
      {
        a.info(String.format("[%d:%d] start failOver branchRollback [%s]", new Object[] { Long.valueOf(j.a(paramb.a())), Long.valueOf(paramb.b()), localb.b() }));
        a(paramb, localb);
        return true;
      }
      catch (Exception localException)
      {
        a.info(String.format("failOver rollback branchId:[%d] [%s] failed.", new Object[] { Long.valueOf(paramb.b()), localb.b() }));
      }
    }
    return false;
  }
  
  private void a(com.taobao.txc.resourcemanager.b.a.b paramb, int paramInt1, int paramInt2, g paramg)
  {
    com.taobao.txc.resourcemanager.b.a.a locala = null;
    try
    {
      for (locala = (com.taobao.txc.resourcemanager.b.a.a)paramb.getConnection();; locala = (com.taobao.txc.resourcemanager.b.a.a)paramb.getConnection())
      {
        int i = locala.a(b, paramInt1, paramInt2);
        paramg.a += i;
        paramg.b += 1L;
        if (i < paramInt2) {
          break;
        }
        if (locala != null) {
          locala.close();
        }
      }
    }
    finally
    {
      if (locala != null) {
        locala.close();
      }
    }
  }
}


/* Location:           C:\Users\ibm\Downloads\txc-yun-sample (1)\txc-yun-sample\lib\txc-client-2.0.72.jar
 * Qualified Name:     com.taobao.txc.resourcemanager.a.f
 * JD-Core Version:    0.7.0.1
 */